package com.cms.support;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: BaseListPageTag
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author zhangp
 * @date 2016年5月3日 上午11:09:32
 * 
 */
public class BaseListPageTag extends BaseDiyTag {
	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = LoggerFactory
			.getLogger(BaseListPageTag.class);

	// 通过父类TagSupport的属性值pageContext 取得相关的内置对象

	private String ajaxUrl;
	private String columns;
	private String titles;
	private String queryTitles;
	private String queryIds;

	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();
		List<String> queryIdList = new LinkedList<String>();
		List<String> queryTitlelList = new LinkedList<String>();
		if (!StringUtils.isEmpty(queryIds)) {
			for (String query : queryIds.split(",")) {
				queryIdList.add(query);
			}
		}
		if (!StringUtils.isEmpty(queryTitles)) {
			for (String query : queryTitles.split(",")) {
				queryTitlelList.add(query);
			}
		}
		try {
			out.println("<div class=\"wrapper wrapper-content animated fadeInRight\">");
			out.println("<div class=\"row\">");
			out.println("<div class=\"col-sm-12\">");
			out.println("<div class=\"ibox float-e-margins\">");

			out.println("<div class=\"ibox-title\">");
			out.println("<form class=\"form-inline form-index\" action=\"#\" method=\"post\" id=\"form\">");
			for (int i = 0; i < queryIdList.size(); i++) {
				String id = queryIdList.get(i);
				if (id.contains("_start") && id.contains("_end")) {// 区间范围的
					if (id.endsWith("-input")) {// 文本类型
						String startId = id.substring(0, id.indexOf("|"));
						String endId = id.substring(id.indexOf("|") + 1);
						out.println("<div class=\"form-group\">");
						out.println("<label class=\"control-label\">"
								+ queryTitlelList.get(i) + "</label>");
						out.println("<input name=\"" + startId + "\" id=\""
								+ startId
								+ "\" type=\"text\"  class=\"form-control\" />");
						out.println("-<input name=\"" + endId + "\" id=\""
								+ endId
								+ "\" type=\"text\"  class=\"form-control\" />");
						out.println("</div>");
					} else if (id.endsWith("-date")) {// 日期类型
						id = id.substring(0, id.lastIndexOf("-"));
						String startId = id.substring(0, id.indexOf("|"));
						String endId = id.substring(id.indexOf("|") + 1);
						out.println("<div class=\"form-group\">");
						out.println("<label class=\"control-label\">"
								+ queryTitlelList.get(i) + "</label>");
						out.println("<input name=\""
								+ startId
								+ "\" id=\""
								+ startId
								+ "\" type=\"text\"  class=\"laydate-icon form-control layer-date\" />");
						out.println("-<input name=\""
								+ endId
								+ "\" id=\""
								+ endId
								+ "\" type=\"text\"  class=\"laydate-icon form-control layer-date\" />");
						out.println("</div>");

						out.println("<script type=\"text/javascript\">");

						out.println("var " + startId + " = {");
						out.println("elem : \"#" + startId + "\",");
						out.println("format : \"YYYY-MM-DD 00:00:00\",");
						out.println("max : \"2099-06-16 23:59:59\",");
						out.println("istime : false,");
						out.println("istoday : true,");
						out.println("choose : function(datas) {");
						out.println(endId + ".min = datas;");
						out.println(endId + ".start = datas;");
						out.println("}");
						out.println("};");
						out.println("laydate(" + startId + ");");

						out.println("var " + endId + " = {");
						out.println("elem : \"#" + endId + "\",");
						out.println("format : \"YYYY-MM-DD 23:59:59\",");
						out.println("min : laydate.now(),");
						out.println("max : \"2099-06-16 23:59:59\",");
						out.println("istime : false,");
						out.println("istoday : true,");
						out.println("choose : function(datas) {");
						out.println(startId + ".max = datas;");
						out.println("}");
						out.println("};");
						out.println("laydate(" + endId + ");");

						out.println("</script>");
					}
				} else {// 单个查询参数
					if (id.endsWith("-input")) {// 文本类型
						id = id.substring(0, id.lastIndexOf("-"));
						out.println("<div class=\"form-group\">");
						out.println("<label class=\"control-label\">"
								+ queryTitlelList.get(i) + "</label>");
						out.println("<input name=\"" + id + "\" id=\"" + id
								+ "\" type=\"text\"  class=\"form-control\" />");
						out.println("</div>");
					} else if (id.endsWith("-date")) {
						id = id.substring(0, id.lastIndexOf("-"));
						out.println("<div class=\"form-group\">");
						out.println("<label class=\"control-label\">"
								+ queryTitlelList.get(i) + "</label>");
						out.println("<input name=\""
								+ id
								+ "\" id=\""
								+ id
								+ "\" type=\"text\"  class=\"laydate-icon form-control layer-date\" />");
						out.println("</div>");

						out.println("<script type=\"text/javascript\">");

						out.println("var " + id + " = {");
						out.println("elem : \"#" + id + "\",");
						out.println("format : \"YYYY-MM-DD 00:00:00\",");
						out.println("max : \"2099-06-16 23:59:59\",");
						out.println("istime : false,");
						out.println("istoday : true,");
						out.println("choose : function(datas) {");
						out.println("}");
						out.println("};");
						out.println("laydate(" + id + ");");

						out.println("</script>");
					} else if (id.contains("-select")) {
						String collectionStr = id
								.substring(id.lastIndexOf("|") + 1);
						String[] mapStrArray = collectionStr.split("/");
						id = id.substring(0, id.lastIndexOf("-"));
						out.println("<div class=\"form-group\">");
						out.println("<label class=\"control-label\">"
								+ queryTitlelList.get(i) + "</label>");
						out.println("<select name=\"" + id + "\" id=\"" + id
								+ "\" class=\"form-control\">");
						out.println("<option value=\"\">全部</option>");
						for (String map : mapStrArray) {
							out.println("<option value=\""
									+ map.substring(0, map.indexOf("_"))
									+ "\">"
									+ map.substring(map.indexOf("_") + 1)
									+ "</option>");
						}
						out.println("</select>");
						out.println("</div>");
					}
				}
			}
			
			//
			// <div class="form-group">
			// <label class="control-label">状态</label>
			// <html:select cssClass="form-control" collection="articleStatus"
			// selectValue="${article.status }" name="status" id="status">
			// <option value="">全部</option>
			// </html:select>
			// </div>

		} catch (IOException e) {
			LOGGER.error("listPageTag error-doStartTag:", e);
		}
		return EVAL_BODY_INCLUDE;
	}

	@Override
	public int doEndTag() throws JspException {
		JspWriter out = pageContext.getOut();
		List<String> coList = new LinkedList<String>();
		List<String> titleList = new LinkedList<String>();
		List<String> queryIdList = new LinkedList<String>();
		List<String> queryTitlelList = new LinkedList<String>();
		if (!StringUtils.isEmpty(columns)) {
			for (String column : columns.split(",")) {
				coList.add(column);
			}
		}
		if (!StringUtils.isEmpty(titles)) {
			titles += ",操作";
			for (String title : titles.split(",")) {
				titleList.add(title);
			}
		}
		if (!StringUtils.isEmpty(queryIds)) {
			for (String query : queryIds.split(",")) {
				queryIdList.add(query);
			}
		}
		if (!StringUtils.isEmpty(queryTitles)) {
			for (String query : queryTitles.split(",")) {
				queryTitlelList.add(query);
			}
		}
		try {
			out.println("<div class=\"form-group button-group\" style=\"width: 100%;\">");
			out.println("<html:auth res=\"" + ajaxUrl + "/list\">");
			out.println("<input onclick=\"reload();\" type=\"button\" id=\"search\" value=\"查询\" class=\"btn btn-default\">");
			out.println("</html:auth>");

			out.println("<html:auth res=\"" + ajaxUrl + "/add\">");
			out.println("<input onclick=\"add();\" type=\"button\" id=\"search\" value=\"新增\" class=\"btn btn-default\">");
			out.println("</html:auth>");

			out.println("<input type=\"reset\" id=\"reset\" value=\"重置\" class=\"btn btn-default\">");
			out.println("</div>");
			out.println("</form>");
			out.println("</div>");
			// 列表html部分
			out.println("<div class=\"ibox-content\">");
			out.println("<table id=\"data\" class=\"table table-striped table-bordered table-hover dataTables-example\">");
			out.println("<thead>");
			out.println("<tr>");
			for (String title : titleList) {
				out.println("<th>" + title + "</th>");
			}
			out.println("</tr>");
			out.println("<thead>");
			out.println("<tbody>");
			out.println("</tbody>");
			out.println("</table>");
			out.println("</div>");

			// js部分
			out.println("<script type=\"text/javascript\">");
			out.println("var table;");
			out.println("function reload() {");
			out.println("table.fnDraw();");
			out.println("}");
			out.println("$(document) .ready( function() {");
			out.println("table = $(\"#data\") .dataTable({");
			out.println("\"bLengthChange\" : false,");// 改变每页显示数据数量
			out.println("\"searching\" : false,");
			out.println("\"bProcessing\" : false,");// 是否显示取数据时的那个等待提示
			out.println("\"bServerSide\" : true,");// 这个用来指明是通过服务端来取数据
			out.println("\"sAjaxSource\" : \"" + ajaxUrl + "/list\",");// 这个是请求的地址
			out.println("\"fnServerData\" : retrieveData,");
			out.println("\"columns\" : [");

			for (int i = 0; i < coList.size(); i++) {
				out.println("{");
				out.println("\"data\" : \"" + coList.get(i) + "\",");
				out.println("\"defaultContent\" :\"\"");
				if (i != coList.size() - 1) {
					out.println("},");
				} else {
					out.println("}],");
				}
			}
			out.println("\"fnServerParams\" : function(aoData) {");
			for (String param : queryIdList) {
				if (param.contains("_start") && param.contains("_end")) {// 区间范围
					param = param.substring(0, param.lastIndexOf("-"));
					String startId = param.substring(0, param.indexOf("|"));
					String endId = param.substring(param.indexOf("|") + 1);
					out.println("aoData.push({");
					out.println("\"name\" : \"" + startId + "\",");
					out.println("\"value\" : $(\"#" + startId + "\").val()");
					out.println("});");

					out.println("aoData.push({");
					out.println("\"name\" : \"" + endId + "\",");
					out.println("\"value\" : $(\"#" + endId + "\").val()");
					out.println("});");

				} else {// 单个查询参数
					param = param.substring(0, param.lastIndexOf("-"));
					out.println("aoData.push({");
					out.println("\"name\" : \"" + param + "\",");
					out.println("\"value\" : $(\"#" + param + "\").val()");
					out.println("});");
				}
			}
			out.println("},");
			out.println("\"columnDefs\" : [");
			out.println("{");
			out.println("\"targets\" : [ " + coList.size() + " ],");
			out.println("\"data\" : \"id\",");
			out.println("\"render\" : function(data, type,full) {");
			out.println("var modify = '<html:auth res=\""
					+ ajaxUrl
					+ "/modify\"><a href=\"#\" onclick=\"modify('+ data+ ')\">修改</a></html:auth>';");
			out.println("var del = '<html:auth res=\""
					+ ajaxUrl
					+ "/del\"><a href=\"#\" onclick=\"del('+ data+ ')\">删除</a></html:auth>';");
			out.println("var view = '<html:auth res=\""
					+ ajaxUrl
					+ "/view\"><a href=\"#\" onclick=\"view('+ data+ ')\">详情</a></html:auth>';");
			out.println("return del+ \"&nbsp;\"+ modify+ \"&nbsp;\"+ view;");
			out.println("} } ] }); });");

			// 3个参数的名字可以随便命名,但必须是3个参数,少一个都不行
			out.println("function retrieveData(url, data, fnCallback) {");
			out.println("$.ajax({");
			out.println("url : url,");
			out.println("data : {");
			out.println("\"iDisplayLength\" : data.iDisplayLength,");
			out.println("\"iDisplayStart\" : data.iDisplayStart,");
			for (int i = 0; i < queryIdList.size(); i++) {
				String id = queryIdList.get(i);
				if (id.contains("_start") && id.contains("_end")) {// 区间范围的
					id = id.substring(0, id.lastIndexOf("-"));
					String startId = id.substring(0, id.indexOf("|"));
					String endId = id.substring(id.indexOf("|") + 1);
					out.println("\"" + startId + "\" : data." + startId);
					out.print(",");
					out.println("\"" + endId + "\" : data." + endId);
				} else {// 单个条件的
					id = id.substring(0, id.lastIndexOf("-"));
					out.println("\"" + id + "\" : data." + id);
				}
				if (i != queryIdList.size() - 1) {
					out.print(",");
				}
			}
			out.println("},");
			out.println("type : 'post',");
			out.println("dataType : 'json',");
			out.println("success : function(result) {");
			out.println("fnCallback(result);");
			out.println("},");
			out.println("error : function(msg) {");
			out.println("}");
			out.println("});}");

			out.println("function add() {");
			out.println("var index = layer.open({");
			out.println("type : 2,");
			out.println("title : \"新增\",");
			out.println("area : [ '800px', '400px' ],");
			out.println("fix : false,");
			out.println("maxmin : true,");
			out.println("content : \"" + ajaxUrl + "/add\"");
			out.println("});");
			out.println("layer.full(index);");
			out.println("}");

			out.println("function modify(id) {");
			out.println("var index = layer.open({");
			out.println("type : 2,");
			out.println("title : \"修改\",");
			out.println("area : [ '800px', '400px' ],");
			out.println("fix : false,");
			out.println("content : \"" + ajaxUrl + "/modify?id=\" + id");
			out.println("});");
			out.println("layer.full(index);");
			out.println("}");

			out.println("function del(id) {");
			out.println("layer.confirm('确定要删除么？', {");
			out.println("btn : [ '确定', '取消' ]");
			out.println("}, function() {");
			out.println("$.ajax({");
			out.println("url : \"" + ajaxUrl + "/del\",");
			out.println("data : {");
			out.println("id : id");
			out.println("},");
			out.println("type : 'post',");
			out.println("ucontentType : 'application/x-www-form-urlencoded',");
			out.println("encoding : 'UTF-8',");
			out.println("cache : false,");
			out.println("success : function(result) {");
			out.println("if (result.success) {");
			out.println("layer.alert('操作成功');");
			out.println("reload();");
			out.println("} else {");
			out.println("layer.alert('操作失败,' + result.obj);");
			out.println("}");
			out.println("},");
			out.println("error : function() {");
			out.println("layer.alert('系统异常');");
			out.println("}");
			out.println("});");
			out.println("}, function() {");
			out.println("});");
			out.println("}");

			out.println("function view(id) {");
			out.println("var index = layer.open({");
			out.println("type : 2,");
			out.println("title : \"详情\",");
			out.println("area : [ '800px', '400px' ],");
			out.println("fix : false,");
			out.println("content : \"" + ajaxUrl + "/view?id=\" + id");
			out.println("});");
			out.println("layer.full(index);");
			out.println("}");

			out.println("</script>");

			out.println("</div>");
			out.println("</div>");
			out.println("</div>");
			out.println("</div>");
		} catch (Exception e) {
			LOGGER.error("baseListPage doEnd error:", e);
		}
		return super.doEndTag();
	}

	public String getAjaxUrl() {
		return ajaxUrl;
	}

	public void setAjaxUrl(String ajaxUrl) {
		this.ajaxUrl = ajaxUrl;
	}

	public String getColumns() {
		return columns;
	}

	public void setColumns(String columns) {
		this.columns = columns;
	}

	public String getTitles() {
		return titles;
	}

	public void setTitles(String titles) {
		this.titles = titles;
	}

	public String getQueryTitles() {
		return queryTitles;
	}

	public void setQueryTitles(String queryTitles) {
		this.queryTitles = queryTitles;
	}

	public String getQueryIds() {
		return queryIds;
	}

	public void setQueryIds(String queryIds) {
		this.queryIds = queryIds;
	}

}
